#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
char commondLine[1024];
char* myargv[64];
int lastCode = 0;
int lastSig = 0;
int main()
{
    int status = 0;
    while(1)
    {
        char* s = fgets(commondLine, 1024 - 1, stdin);
        assert(s != NULL);
        (void*)s;
        //把读入的换行符变成'\0'
        commondLine[strlen(commondLine) - 1] = 0;
        myargv[0] = strtok(commondLine, " ");
        int i = 1;
        //当执行ls指令时，自动带上颜色选项
        if(myargv[0] != NULL && strcmp(myargv[0], "ls") == 0)
            myargv[i++] = "--color=auto";
        
        //把NULL也读入，并且此时读入结束
        while(myargv[i++] = strtok(NULL, " "));
        //内建命令cd echo等等，不需要创建子进程来执行
        if(myargv[0] != NULL && strcmp(myargv[0], "cd") == 0)
        {
            if(myargv[1] != NULL)
            {
                chdir(myargv[1]);
            }
            continue;
        }
        if(myargv[0] != NULL && myargv[1] != NULL && strcmp(myargv[0], "echo") == 0)
        {
            if(strcmp(myargv[1], "$?") == 0)
                printf("%d %d\n", lastCode, lastSig);
            else
                printf("%s\n", myargv[1]);
            continue;
        }
#ifdef DEBUG
for(int j = 0; myargv[j]; j++)
{
    printf("argv[%d]: %s\n", j, myargv[j]);
}        
#endif
        pid_t id = fork();
        assert(id != -1);
        if(id == 0)
        {
            execvp(myargv[0], myargv);
            _exit(0);
        }
        pid_t ret = waitpid(id, &status, 0);
        assert(ret != -1);
        lastCode = status >> 8 & 0xff;
        lastSig = status & 0x7f;
    }
}